﻿using MemberManagement.Common;
using MemberManagement.Context;
using MemberManagement.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MemberManagement
{
    public partial class ConsumptionForm : Form
    {
        public string MemberId { get; set; }

        private bool IsSave = false;

        private Member _member;
        public ConsumptionForm()
        {
            InitializeComponent();
            this.comboName.DisplayMember = "Name";
        }
        private void ConsumptionForm_Load(object sender, EventArgs e)
        {
            this.GetParam();
            if (!string.IsNullOrEmpty(MemberId))
            {
                var member = GetMemberDetail(MemberId);
                this.comboName.Enabled = false;
                this.comboName.DataSource = new List<Member> { member };
                this.comboName.SelectedItem = member;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.IsSave)
            {
                MessageBox.Show($"正在处理上一笔，请稍后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.IsSave = true;
            ((Button)sender).Enabled = false;
            this.UpdateMember();
            ((Button)sender).Enabled = true;
            this.IsSave = false;
            this.txtCardNumber.Focus();
        }

        private void comboName_TextUpdate(object sender, EventArgs e)
        {
            //清空combobox
            ResetForm();
            this.GetComboNameList(this.comboName.Text);
            //设置光标位置，否则光标位置始终保持在第一列，造成输入关键词的倒序排列
            this.comboName.SelectionStart = this.comboName.Text.Length;
            //保持鼠标指针原来状态，有时候鼠标指针会被下拉框覆盖，所以要进行一次设置。
            Cursor = Cursors.Default;
            //自动弹出下拉框
            this.comboName.DroppedDown = true;
        }

        private void comboName_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectMember = this.comboName.SelectedItem as Member;
            if (selectMember != null)
            {
                this.txtCardNumber.Text = selectMember.CardNumber;
                this.txtIdCard.Text = selectMember.IdCard;
                this.txtMobile.Text = selectMember.Mobile;
                this.txtBalance.Value = selectMember.Balance;
            }
        }

        private void ResetForm()
        {
            this.comboName.DataSource = new List<Member>();
            this.comboName.SelectedItem = null;
            this.txtCardNumber.Text = string.Empty;
            this.txtIdCard.Text = string.Empty;
            this.txtMobile.Text = string.Empty;
            this.txtBalance.Value = 0M;
            this.txtAmount.Value = 0M;
            this.txtRemark.Text = string.Empty;
        }

        private bool UpdateMember()
        {
            try
            {
                using (var db = new MyContext())
                {
                    Member selectMember = this.comboName.SelectedItem as Member;
                    if (selectMember == null) throw new Exception("请先选择一个会员");
                    var member = db.Member.FirstOrDefault(m => m.Id == selectMember.Id);
                    if (member == null) throw new Exception("找不到当前会员信息");
                    if(member.Balance < this.txtBalance.Value) throw new Exception("扣费失败，余额不足");
                    member.Balance -= this.txtAmount.Value;
                    db.Update(member);
                    db.Recharge.Add(new Recharge()
                    {
                        MemberId = member.Id,
                        Type = Entity.Enum.RechargeType_Enum.Consumption,
                        Amount = this.txtAmount.Value,
                        Balance = member.Balance,
                        Remark = this.txtRemark.Text
                    });

                    db.SaveChanges();
                    MessageBox.Show($"{member.Name} 刷卡扣费成功! 余额：{member.Balance.ToString("F2")}", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        private void GetComboNameList(string name = null)
        {
            using (var db = new MyContext())
            {
                var query = db.Member.Where(m => true)
                    .OrderByDescending(m => m.CreateTime)
                    .AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(m => m.Name.Contains(name));
                }
                var result = query.Take(20).ToArray();
                this.comboName.DataSource = result;
            }
        }

        private bool GetParam()
        {
            try
            {
                using (var db = new MyContext())
                {
                    var amountConfig = db.SysConfig.FirstOrDefault(o => o.Key == ConstKey.AmountKey);
                    if (amountConfig == null)
                    {
                        MessageBox.Show("请先配置扣费金额。参数名：amount", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.btnSave.Visible = false;
                    }
                    else
                    {
                        decimal.TryParse(amountConfig.Value,out decimal amount);
                        this.txtAmount.Value = amount;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        private Member GetMemberDetail(string memberId)
        {
            try
            {
                using (var db = new MyContext())
                {
                    var member = db.Member.FirstOrDefault(m => m.Id == memberId);
                    this._member = member;
                    if (member == null) throw new Exception("当前会员不存在");
                    return member;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
    }
}
